<template>
  <view class="price-management">
    <!-- 筛选条件 -->
    <view class="filter-bar">
      <picker @change="changePriceType" :value="filter.price_type" :range="priceTypes">
        <view class="filter-item">
          {{priceTypes[filter.price_type]}} <uni-icons type="arrowdown" size="14"></uni-icons>
        </view>
      </picker>
      
      <picker @change="changeDepot" :value="filter.depot_id" :range="depots" range-key="name">
        <view class="filter-item">
          {{filter.depot_id ? selectedDepot.name : '全部站点'}} <uni-icons type="arrowdown" size="14"></uni-icons>
        </view>
      </picker>
      
      <picker @change="changeSizeType" :value="filter.size_type" :range="sizeTypes">
        <view class="filter-item">
          {{filter.size_type? sizeTypes[filter.size_type] : '全部箱型'}} <uni-icons type="arrowdown" size="14"></uni-icons>
        </view>
      </picker>
      
      <button class="add-btn" @click="addPriceRule">新增规则</button>
    </view>
    
    <!-- 价格规则列表 -->
    <scroll-view scroll-y class="price-list">
      <view v-for="(rule, index) in priceRules" :key="index" class="price-card">
        <view class="card-header">
          <text class="rule-title">{{getRuleTitle(rule)}}</text>
          <view class="status-badge" :class="rule.status ? 'active' : 'inactive'">
            {{rule.status ? '启用中' : '已停用'}}
          </view>
        </view>
        
        <view class="card-body">
          <view class="price-info">
            <text class="price-value">¥{{rule.price.final_price}}</text>
            <text class="price-desc">{{getPriceDescription(rule)}}</text>
          </view>
          
          <view class="scope-info">
            <text v-if="rule.scope.depot_id" class="scope-item">
              <uni-icons type="shop" size="14" color="#666"></uni-icons>
              {{getDepotName(rule.scope.depot_id)}}
            </text>
            <text v-if="rule.scope.size_type !== undefined" class="scope-item">
              <uni-icons type="box" size="14" color="#666"></uni-icons>
              {{sizeTypes[rule.scope.size_type]}}
            </text>
            <text v-if="rule.scope.member_level !== undefined" class="scope-item">
              <uni-icons type="vip" size="14" color="#666"></uni-icons>
              {{memberLevels[rule.scope.member_level]}}
            </text>
          </view>
          
          <view class="duration-info">
            <text>租期: {{rule.duration.value}} {{durationUnits[rule.duration.unit]}}</text>
            <text v-if="rule.duration.min_duration">(最短{{rule.duration.min_duration}})</text>
          </view>
          
          <view v-if="rule.overtime_rules.length" class="overtime-info">
            <text>超时规则:</text>
            <view v-for="(overtime, idx) in rule.overtime_rules" :key="idx" class="overtime-item">
              超时{{overtime.threshold}}分钟: {{formatOvertimeRule(overtime)}}
            </view>
          </view>
          
          <view v-if="rule.renewal_rules" class="renewal-info">
            <text>续期规则: {{rule.renewal_rules.renewal_price}}元/{{durationUnits[rule.renewal_rules.renewal_unit]}}</text>
            <text v-if="rule.renewal_rules.max_renewal">(最多续{{rule.renewal_rules.max_renewal}}次)</text>
          </view>
          
          <view class="effective-info">
            <text>生效: {{formatDate(rule.effective_date)}}</text>
            <text v-if="rule.expire_date">至 {{formatDate(rule.expire_date)}}</text>
          </view>
        </view>
        
        <view class="card-footer">
          <button class="edit-btn" @click="editRule(rule)">编辑</button>
          <button class="status-btn" @click="toggleStatus(rule)">
            {{rule.status ? '停用' : '启用'}}
          </button>
        </view>
      </view>
    </scroll-view>
    
    <!-- 添加/编辑弹窗 -->
    <uni-popup ref="editPopup" type="bottom">
      <PriceRuleEditor 
        :rule="editingRule"
        :depots="depots"
        @save="savePriceRule"
        @cancel="closeEditor"
      />
    </uni-popup>
  </view>
</template>

<script>
import PriceRuleEditor from './add.vue'
const db = uniCloud.databaseForJQL() //代码块为cdb
export default {
  components: { PriceRuleEditor },
  data() {
    return {
      filter: {
        price_type: 0,
        depot_id: null,
        size_type: null
      },
      priceRules: [],
      depots: [],
      editingRule: null,
      priceTypes: ['基础价格', '续期价格', '超时价格', '会员价格', '套餐价格', '节假日价格'],
      sizeTypes: ['小箱型', '中箱型', '大箱型'],
      durationUnits: ['小时', '天', '周', '月'],
      memberLevels: ['普通会员', '白银会员', '黄金会员', '钻石会员']
    }
  },
  computed: {
    selectedDepot() {
      return this.depots.find(d => d._id === this.filter.depot_id) || {}
    }
  },
  async onLoad() {
    await this.loadDepots()
    this.loadPriceRules()
  },
  methods: {
    async loadDepots() {
		db.collection('mydb-depot-list')
			.where('status==1')
			.get()
			.then((res)=>{
			// res 为数据库查询结果
			console.log('depots',res)
			this.depots = res.data
			}).catch((err)=>{
				console.log(err.code); // 打印错误码
				console.log(err.message); // 打印错误内容
		  })
    },
    
    async loadPriceRules() {
      uni.showLoading({ title: '加载中...' })
      try {
        const params = {
          price_type: this.filter.price_type,
          depot_id: this.filter.depot_id,
          size_type: this.filter.size_type
        }
        db.collection('mydb-price-rules')
        	.where({...params})
        	.get()
        	.then((res)=>{
        	// res 为数据库查询结果
        	this.priceRules = res.data
        	}).catch((err)=>{
        		console.log(err.code); // 打印错误码
        		console.log(err.message); // 打印错误内容
          })
        this.priceRules = res.data
      } catch (err) {
        console.log(err);  // 打印错误内容
      } finally {
        uni.hideLoading()
      }
    },
    
    getRuleTitle(rule) {
      const titles = {
        0: '基础价格',
        1: '续期价格',
        2: '超时价格',
        3: `会员优惠 (${this.memberLevels[rule.scope.member_level]})`,
        4: '套餐价格',
        5: '节假日价格'
      }
      return titles[rule.price_type] || '价格规则'
    },
    
    getPriceDescription(rule) {
      if (rule.price.discount_type === 0) {
        return `(${rule.price.discount_value * 10}折优惠)`
      } else if (rule.price.discount_type === 1) {
        return `(减${rule.price.discount_value}元)`
      }
      return ''
    },
    
    getDepotName(depotId) {
      const depot = this.depots.find(d => d._id === depotId)
      return depot ? depot.name : '未知站点'
    },
    
    formatOvertimeRule(overtime) {
      const types = {
        0: `固定¥${overtime.penalty_value}`,
        1: `基础价${overtime.penalty_value}倍/小时`,
        2: `额外${overtime.penalty_value * 100}%费率`
      }
      return types[overtime.penalty_type] || ''
    },
    
    formatDate(timestamp) {
      if (!timestamp) return ''
      const date = new Date(timestamp)
      return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`
    },
    
    addPriceRule() {
      this.editingRule = {
        price_type: 0,
        scope: {},
        duration: {
          unit: 0,
          value: 1
        },
        price: {
          base_price: 0,
          discount_type: 0,
          discount_value: 1,
          final_price: 0
        },
        overtime_rules: [],
        renewal_rules: null,
        effective_date: Date.now(),
        expire_date: null,
        priority: 0,
        status: 1
      }
      this.$refs.editPopup.open()
    },
    
    editRule(rule) {
      this.editingRule = JSON.parse(JSON.stringify(rule))
      this.$refs.editPopup.open()
    },
    
    async savePriceRule(rule) {
      uni.showLoading({ title: '保存中...' })
      try {
        const method = rule._id ? 'update' : 'create'
		const res = method=='create' ? await db.collection('mydb-price-rules').add({...rule}) : await db.collection('mydb-price-rules').where({_id:rule._id}).update({...rule})
        if (res.code === 0) {
          uni.showToast({ title: '保存成功' })
          this.loadPriceRules()
          this.closeEditor()
        } else {
          uni.showToast({
            title: res.message || '保存失败',
            icon: 'none'
          })
        }
      } catch (e) {
        uni.showToast({
          title: '保存失败',
          icon: 'none'
        })
      } finally {
        uni.hideLoading()
      }
    },
    
    async toggleStatus(rule) {
      const newStatus = rule.status ? 0 : 1
      uni.showLoading({ title: '更新中...' })
      try {
        const res = await db.collection('mydb-price-rules').where({_id:rule._id}).update({status: newStatus})
        if (res.code === 0) {
          rule.status = newStatus
          uni.showToast({ title: '状态已更新' })
        } else {
          uni.showToast({
            title: '更新失败',
            icon: 'none'
          })
        }
      } catch (e) {
        uni.showToast({
          title: '更新失败',
          icon: 'none'
        })
      } finally {
        uni.hideLoading()
      }
    },
    
    closeEditor() {
      this.$refs.editPopup.close()
      this.editingRule = null
    },
    
    changePriceType(e) {
      this.filter.price_type = e.detail.value
      this.loadPriceRules()
    },
    
    changeDepot(e) {
      this.filter.depot_id = e.detail.value>-1 ? this.depots[e.detail.value]._id : null
      this.loadPriceRules()
    },
    
    changeSizeType(e) {
      this.filter.size_type = e.detail.value
      this.loadPriceRules()
    }
  }
}
</script>

<style lang="scss">
.price-management {
  padding: 15px;
  background: #f8f8f8;
  min-height: 100vh;
}

.filter-bar {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 15px;
  gap: 10px;
  
  .filter-item {
    background: #fff;
    border-radius: 20px;
    padding: 8px 15px;
    font-size: 14px;
    display: flex;
    align-items: center;
    box-shadow: 0 2px 5px rgba(0,0,0,0.05);
  }
  
  .add-btn {
    background: #FF7F00;
    color: #fff;
    border-radius: 20px;
    font-size: 14px;
    padding: 0 15px;
    height: 36px;
    line-height: 36px;
  }
}

.price-list {
  height: calc(100vh - 150px);
}

.price-card {
  background: #fff;
  border-radius: 12px;
  margin-bottom: 15px;
  overflow: hidden;
  box-shadow: 0 2px 10px rgba(0,0,0,0.05);
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 15px;
    background: #FFF5EB;
    border-bottom: 1px solid #f0f0f0;
    
    .rule-title {
      font-size: 16px;
      font-weight: bold;
      color: #FF7F00;
    }
    
    .status-badge {
      font-size: 12px;
      padding: 3px 8px;
      border-radius: 10px;
      
      &.active {
        background: #4CAF50;
        color: #fff;
      }
      
      &.inactive {
        background: #9E9E9E;
        color: #fff;
      }
    }
  }
  
  .card-body {
    padding: 15px;
    
    .price-info {
      display: flex;
      align-items: baseline;
      margin-bottom: 10px;
      
      .price-value {
        font-size: 24px;
        font-weight: bold;
        color: #FF7F00;
        margin-right: 8px;
      }
      
      .price-desc {
        font-size: 14px;
        color: #FF9E40;
      }
    }
    
    .scope-info {
      display: flex;
      flex-wrap: wrap;
      gap: 10px;
      margin-bottom: 10px;
      
      .scope-item {
        background: #f5f5f5;
        border-radius: 12px;
        padding: 4px 10px;
        font-size: 12px;
        display: flex;
        align-items: center;
      }
    }
    
    .duration-info, .overtime-info, .renewal-info, .effective-info {
      font-size: 13px;
      color: #666;
      margin-bottom: 8px;
      display: flex;
      flex-wrap: wrap;
      gap: 5px;
    }
    
    .overtime-item {
      width: 100%;
      padding-left: 10px;
    }
  }
  
  .card-footer {
    display: flex;
    padding: 10px 15px;
    border-top: 1px solid #f0f0f0;
    
    button {
      flex: 1;
      height: 36px;
      line-height: 36px;
      font-size: 14px;
      border-radius: 18px;
      margin: 0 5px;
      
      &.edit-btn {
        background: #fff;
        color: #FF7F00;
        border: 1px solid #FF7F00;
      }
      
      &.status-btn {
        background: #FF7F00;
        color: #fff;
      }
    }
  }
}
</style>